package com.Modular.pdf_Util.examplesPDF.CheLiangSanChaJiLu;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.Modular.MinioPlugin.MinIoOperations;
import com.Modular.pdf_Util.PDF_utils;
import com._Config.Model.errorLogModel;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.jfinal.core.Controller;
import com.jfinal.log.Log4jLog;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * 车辆调度日志登记
 */
public class CheLiangSanChaJiLuService extends Controller {
    static Log4jLog logger = Log4jLog.getLog(CheLiangSanChaJiLuService.class);

    String dir = System.getProperty("user.dir");
    public static final CheLiangSanChaJiLuService service = new CheLiangSanChaJiLuService();
    private final Random random = new Random(10000);

    public String buildPdf(String chePaiHaoMa, String startTime) {
        List<String> urlList = new ArrayList<>();
        try {
            if (startTime == null) {//默认当天时间
                startTime = DateUtil.format(new Date(), "yyyy-MM-dd");
            }
            startTime = DateUtil.format(DateUtil.parse(startTime).toJdkDate(), "yyyy-MM-dd") + " 00:00:00";
            String endTime = DateUtil.format(DateUtil.parse(startTime).toJdkDate(), "yyyy-MM-dd") + " 23:59:59";

            List<errorLogModel> dataList
                    = errorLogModel.dao.find("SELECT * FROM T_AnQuanShengChanRiChangGuanLi_CheLiangAnQuanJianCha " +
                            " WHERE sys_xitongzhuangtai=0 and ChePaiHaoMa=? AND JainChaLeiXing IN('车辆出场检查','车辆回场检查','车辆途中检查','0','2','1') and JianChaRiQi >=? and JianChaRiQi<=? ORDER BY JianChaRiQi ASC "
                    , chePaiHaoMa, startTime, endTime); //JainChaLeiXing in('0','2','1')
            //如数据在当天达不到数据每组数据有三条，则到库里取最新一条 车辆途中检查、车辆回场检查；
            //dataList.size()%3不等于0，取跨天数据，1条或2条； 一条时为：车辆回场检查，两条为：车辆途中检查、车辆回场检查
            int size = dataList.size();
            int remaining = size % 3; //等1，缺两条数据； 等2，缺一条数据
            if (remaining != 0) { //数据是否缺失
                //追加跨天数据   1条或2条
                int limit = 1;
                if (remaining == 1) {
                    limit = 2;
                }
                List<errorLogModel>
                        list = queryLastData(chePaiHaoMa, endTime, limit);
                logger.warn("缺失数据：%d 条，找到的最新数据：%d 条", limit, list.size());
                if (limit != list.size()) {
                    logger.warn("在跨天中并未找到缺失所有数据，需：%d 条，找到：%d 条", limit, list.size());
                }
                dataList.addAll(list);
            }

            //必须每组三种数据，每三条数据一组，生成一个pdf
            for (int i = 0; i < dataList.size() / 3; i++) {
                int x = 0;
                List<errorLogModel> gList = new ArrayList<>();
                for (int j = i == 0 ? (0) : (i * 2) + i; j < dataList.size(); j++) {
                    x++;
                    gList.add(dataList.get(j));
                    if (x == 3) {
                        String url = build(gList, startTime, chePaiHaoMa);
                        urlList.add(url);
                        System.out.println("------------");
                        break;
                    }
                }
            }

            String path = File.createTempFile(String.valueOf(random.nextInt()), ".pdf").getAbsolutePath();
            morePdfTopdf(urlList, path);
            String time = DateFormatUtils.format(new Date(), "yyyy-MM-dd-SSS");
            String pdfName = String.format("%s.pdf", "车辆三检记录表-" + chePaiHaoMa + time + random.nextInt());
            MinIoOperations.fileUpload("asiatrip", pdfName, path);
            String geturl = MinIoOperations.fileGeturlGet("asiatrip", pdfName);

            //入库关联电子档案
            String SYS_DanWeiMingCheng = null, danWeiDaiMa = null, SYS_DanWeiDianNaoBianHao = null;
            if (dataList.size() > 0) {
                SYS_DanWeiMingCheng = dataList.get(0).getStr("SYS_DanWeiMingCheng");
                danWeiDaiMa = dataList.get(0).getStr("SYS_DanWeiDaiMa");
                SYS_DanWeiDianNaoBianHao = dataList.get(0).getStr("SYS_DanWeiDianNaoBianHao");
            }
            //关连电子档案
            dangAnWenJian("车辆三检记录表", pdfName, geturl, SYS_DanWeiDianNaoBianHao, SYS_DanWeiMingCheng, danWeiDaiMa);
            return geturl;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成pdf
     *
     * @param dataList    数据
     * @param startTime   开始时间
     * @param chePaiHaoMa 车牌号
     * @return
     * @throws Exception
     */
    public String build(List<errorLogModel> dataList, String startTime, String chePaiHaoMa) throws Exception {
        Map<String, String> titleMap = new HashMap<>();
        String time = DateFormatUtils.format(new Date(), "yyyy-MM-dd-SSS");
        List<Map<String, Object>> chuList = new ArrayList<>();
        List<Map<String, Object>> jinList = new ArrayList<>();
        List<Map<String, Object>> tuList = new ArrayList<>();
        titleMap = chuChang(dataList, startTime, chePaiHaoMa, chuList, jinList, tuList);

        String fileName = String.format("%s%s.pdf", "车辆三检记录表", DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + random.nextInt());
        String outPath =File.createTempFile(fileName.replace(".pdf",""),".pdf").getAbsolutePath();
//        String pdfName = String.format("%s.pdf", "车辆三检记录表-" + chePaiHaoMa + time + random.nextInt());
        //生成本地pdf 一表单+一表格
        PDF_utils.buildPdf("车辆三检记录表-模板.docx", outPath, titleMap, 2, chuList, tuList, jinList);
        logger.debug("fileName:%s,output:%s", fileName, outPath);

        return outPath;
    }

    /**
     * 查询跨天的最新记录
     *
     * @param chePaiHaoMa
     * @param endTime
     */
    public List<errorLogModel> queryLastData(String chePaiHaoMa, String endTime, int limit) {
        List<errorLogModel> dataList
                = errorLogModel.dao.find("SELECT * FROM T_AnQuanShengChanRiChangGuanLi_CheLiangAnQuanJianCha " +
                        " WHERE sys_xitongzhuangtai=0 and ChePaiHaoMa=? " +
                        " AND JainChaLeiXing IN('车辆回场检查','车辆途中检查','2','1') and JianChaRiQi > ? ORDER BY JianChaRiQi ASC LIMIT ?"
                , chePaiHaoMa, endTime, limit);//JainChaLeiXing in('2','1')
        return dataList;
    }

    public Map<String, String> chuChang(List<errorLogModel> dataList, String startTime, String chePaiHaoMa, List<Map<String, Object>> chuList,
                                        List<Map<String, Object>> jinList, List<Map<String, Object>> tuList) {
//        String startTime = "2022-04-21 00:00:00";
//        String endTime = "2022-04-21 23:59:59";

        Map<String, String> dataMap = new HashMap<>();
        String time = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        errorLogModel singeModel = null;
        if (dataList.size() > 0) {
            singeModel = dataList.get(0);
        }
        dataMap.put("JianChaRiQi", "");
        dataMap.put("Time", time);
        dataMap.put("ChePaiHaoMa", chePaiHaoMa);
        if (singeModel != null) {
            dataMap.put("QiYeMingCheng", singeModel.getStr("QiYeMingCheng") == null ? "" : singeModel.getStr("QiYeMingCheng"));
            dataMap.put("ChePaiYanSe", singeModel.getStr("ChePaiYanSe") == null ? "" : singeModel.getStr("ChePaiYanSe"));
            dataMap.put("CheDuiZhang", singeModel.getStr("CheDuiZhang") == null ? "" : singeModel.getStr("CheDuiZhang"));
            dataMap.put("DangBanJiaShiYuan", singeModel.getStr("DangBanJiaShiYuan") == null ? "" : singeModel.getStr("DangBanJiaShiYuan"));
        }
        for (errorLogModel
                model : dataList) {
            String leiXing = model.getStr("JainChaLeiXing");
            String jianChaJson = model.getStr("JianChaNeiRong");
            JSONArray json = JSONUtil.parseArray(jianChaJson);
            for (int i = 0; i < json.size(); i++) {
                Map<String, Object> data = new HashMap<>();
                JSONObject m = json.getJSONObject(i);
                String key = m.getStr("CanShuMingCheng");
                String jieGuo = m.getStr("JieGuo");
                data.put("key", key);
                data.put("value", jieGuo == null ? "" : jieGuo);
                data.put("ShuoMing", m.getStr("ShuoMing") == null ? "" : m.getStr("ShuoMing"));
                data.put("num", i);
                if ("车辆出场检查".equals(leiXing)||"0".equals(leiXing)) {
                    dataMap.put("ChuCheRiQi", model.getStr("JianChaRiQi"));
                    chuList.add(data);
                } else if ("车辆回场检查".equals(leiXing)||"2".equals(leiXing)) {
                    dataMap.put("ShouCheRiQi", model.getStr("JianChaRiQi"));
                    jinList.add(data);
                } else if ("车辆途中检查".equals(leiXing) ||"1".equals(leiXing)) {
                    tuList.add(data);
                }
            }
        }
        return dataMap;
    }

    //关连电子档案
    public void dangAnWenJian(String muLuName, String fileName, String filePath, String SYS_DanWeiDianNaoBianHao,
                              String SYS_DanWeiMingCheng, String SYS_DanWeiDaiMa) {
        //创建文件记录（电子档案）
    	errorLogModel fileModel = new errorLogModel();
        fileModel.set("Id", IdUtil.randomUUID());
        fileModel.set("ZhuId", "13b8805f-2dd9-46dd-ac10-e4d409ac1116");//车辆安全检查
        fileModel.set("WenJianZiLei",muLuName);
        fileModel.set("WenJianLeiBie","隐患排查与治理");
        fileModel.set("WenJianMingCheng", fileName);
        fileModel.set("WenJianLaiYuan", "系统生成");
        fileModel.set("WenJianWeiZhi", filePath);
        fileModel.set("SYS_DanWeiDianNaoBianHao", SYS_DanWeiDianNaoBianHao);
        fileModel.set("SYS_DanWeiMingCheng", SYS_DanWeiMingCheng);
        fileModel.set("SYS_DanWeiDaiMa", SYS_DanWeiDaiMa);
        fileModel.set("GengXinShiJian", new Date());
        fileModel.set("BianHao", 1);
        fileModel.save();
    }

    public static void morePdfTopdf(List<String> fileList, String savepath) {
        Document document = null;
        try {
            if(fileList==null||fileList.size()==0){
                return;
            }
            document = new Document(new PdfReader(fileList.get(0)).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(savepath));
            document.open();
            for (int i = 0; i < fileList.size(); i++) {
                PdfReader reader = new PdfReader(fileList.get(i));
                int n = reader.getNumberOfPages();// 获得总页码
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);// 从当前Pdf,获取第j页
                    copy.addPage(page);
                }
                reader.close();
            }
            copy.close();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                document.close();
            }
            System.out.println("finish " + new Date());
        }
    }
}